/*
 * @Author: lei
 * @Description: 使用正则库解析配置文件示例 
 * @FilePath: /9-11/config.cc
 */

#include <iostream>
#include <fstream>
#include <string>
#include <regex>
#include <unordered_map>
using namespace std;

//g++ -o config config.cc -std=c++11
class Config
{
public:
    bool PullConfig(const string& filename)
    {
        ifstream s(filename, s.binary | s.out);
        if (!s.is_open()) 
        {
            std::cout << "failed to open " << filename << '\n';
            return false;
        } 
        while(getline(s,buf))
            Parse_line();
        return true;
    }
    void OutputConfig()
    {
        for(auto& v : mp)
        {
            cout << "key=" << v.first << ",value=" << v.second << endl;
        }
    }
private:
    unordered_map<string,string> mp;
    string buf;

    void Parse_line()
    {
        smatch matches;
        std::regex regex1("^([^ =]*)[^\\d]*(\\d+.*)");// \d是特殊字符，所以这里要转义
        if(regex_search(buf,matches,regex1))
        {
            mp[matches.str(1)] = matches.str(2);
        } 
    }
};

int main()
{
    Config config;
    if(config.PullConfig("test.conf"))
    {
        config.OutputConfig();
    }
    return 0;
}
